#include "stringbad.h"
#include <cstring>

using std::cout;

int StringBad::num_strings = 0;

StringBad::StringBad(const char * s)
{
    len = std::strlen(s);
    str = new char[len + 1];
    std::strcpy(str, s);

    ++num_strings;
    cout << num_strings << ": " << str << " object create" << std::endl;
}
StringBad::StringBad()
{
    len = 4;
    str = new char[4];
    strcpy(str, "C++");

    ++num_strings;
    cout << num_strings << ": " << str << " object create" << std::endl;
}
StringBad::~StringBad()
{
    --num_strings;
    cout << str << " object deleted, " << num_strings << " left" << std::endl;

    delete [] str;
}

std::ostream & operator<<(std::ostream & os, const StringBad & st)
{
    os << st.str;
    return os;
}

// copy instructor
StringBad::StringBad(const StringBad & st)
{
    // 深拷贝
    len = st.len;
    str = new char[len + 1];
    std::strcpy(str, st.str);

    ++num_strings;
    cout << num_strings << ": " << str << " object created" << std::endl;
}

StringBad & StringBad::operator=(const StringBad & st)
{
    if (this == &st)
        return *this;
    
    delete [] str;

    len = st.len;
    str = new char[len + 1];
    std::strcpy(str, st.str);

    return *this;
}